<template>
  <div class="exam-taking-container">
    <!-- 考试头部信息 -->
    <div class="exam-header">
      <div class="exam-info">
        <h2>{{ exam?.title }}</h2>
        <div class="exam-meta">
          <el-tag>{{ exam?.examType }}</el-tag>
          <span>总分：{{ exam?.totalPoints }}分</span>
          <span>及格线：{{ exam?.passScore }}分</span>
        </div>
      </div>
      <div class="exam-timer" v-if="exam?.timeLimit">
        <el-statistic 
          title="剩余时间" 
          :value="timeRemaining" 
          format="mm:ss"
          :value-style="{ color: timeRemaining < 300000 ? '#f56c6c' : '#409eff' }"
        />
      </div>
    </div>

    <!-- 题目区域 -->
    <div class="questions-section" v-if="questions && questions.length > 0">
      <aside class="ka-aside">
        <div class="ka-timer" v-if="exam?.timeLimit">
          <div class="label">剩余时间</div>
          <div class="time" :class="{ danger: timeRemaining < 300000 }">
            {{ Math.floor(timeRemaining/60000).toString().padStart(2,'0') }}:{{ Math.floor((timeRemaining%60000)/1000).toString().padStart(2,'0') }}
          </div>
        </div>
        <div class="ka-nav">
          <button 
            v-for="(q, index) in questions" 
            :key="q.id"
            class="ka-nav-btn"
            :class="{ active: currentQuestionIndex === index, done: !!answers[q.id] }"
            @click="goToQuestion(index)"
          >{{ index + 1 }}</button>
        </div>
        <div class="ka-submit">
          <el-button type="danger" @click="submitExam" :loading="submitting" style="width:100%">提交考试</el-button>
        </div>
      </aside>

      <div class="current-question">
        <div class="question-header">
          <h3>第 {{ currentQuestionIndex + 1 }} 题 ({{ currentQuestion?.points }}分)</h3>
          <el-tag :type="getDifficultyColor(currentQuestion?.difficulty)">
            {{ getDifficultyText(currentQuestion?.difficulty) }}
          </el-tag>
        </div>

        <div class="question-content">
          <div class="question-title">{{ currentQuestion?.title }}</div>
          <div class="question-text" v-html="currentQuestion?.content"></div>
          
          <!-- 选择题 -->
          <div v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(currentQuestion?.questionType)" class="options">
            <el-radio-group 
              v-if="currentQuestion.questionType === 'SINGLE_CHOICE'"
              v-model="answers[currentQuestion.id]"
              @change="saveAnswer(currentQuestion.id, $event)"
            >
              <el-radio 
                v-for="([key, option], idx) in getShuffledOptions(currentQuestion)" 
                :key="key"
                :label="key"
                class="option-item"
              >
                {{ option.content || option }}
              </el-radio>
            </el-radio-group>

            <el-checkbox-group 
              v-else
              v-model="answers[currentQuestion.id]"
              @change="saveAnswer(currentQuestion.id, $event)"
            >
              <el-checkbox 
                v-for="([key, option], idx) in getShuffledOptions(currentQuestion)" 
                :key="key"
                :label="key"
                class="option-item"
              >
                {{ option.content || option }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <!-- 判断题 -->
          <div v-else-if="currentQuestion?.questionType === 'TRUE_FALSE'" class="true-false">
            <el-radio-group 
              v-model="answers[currentQuestion.id]"
              @change="saveAnswer(currentQuestion.id, $event)"
            >
              <el-radio :label="true">正确</el-radio>
              <el-radio :label="false">错误</el-radio>
            </el-radio-group>
          </div>

          <!-- 填空题和问答题 -->
          <div v-else class="text-answer">
            <el-input
              v-model="answers[currentQuestion.id]"
              type="textarea"
              :rows="4"
              placeholder="请输入答案"
              @blur="saveAnswer(currentQuestion.id, answers[currentQuestion.id])"
            />
          </div>
        </div>

        <!-- 导航按钮 -->
        <div class="question-navigation-buttons">
          <el-button 
            @click="previousQuestion" 
            :disabled="currentQuestionIndex === 0"
          >
            上一题
          </el-button>
          <el-button 
            @click="nextQuestion" 
            :disabled="currentQuestionIndex === questions.length - 1"
          >
            下一题
          </el-button>
        </div>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="exam-footer">
      <el-button type="danger" @click="submitExam" :loading="submitting">提交考试</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { examApi } from '@/api/exam'
import { getErrorMessage } from '@/api/http'

const route = useRoute()
const router = useRouter()
const examId = Number(route.params.id)

// 响应式数据
const exam = ref<any>(null)
const record = ref<any>(null)
const questions = ref<any[]>([])
const answers = ref<Record<number, any>>({})
const currentQuestionIndex = ref(0)
const timeRemaining = ref(0)
const timer = ref<NodeJS.Timeout | null>(null)
const submitting = ref(false)

// 乱序缓存：保证同一题在刷新期间顺序稳定
const optionOrderCache = ref<Record<number, string[]>>({})

// 计算属性
const currentQuestion = computed(() => questions.value[currentQuestionIndex.value])

// 方法
const getAnswersKey = () => {
  const id = record.value?.id ?? `exam_${examId}`
  return `exam_answers_${id}`
}

const getTimeKey = () => {
  const id = record.value?.id ?? `exam_${examId}`
  return `exam_time_${id}`
}

const loadDraft = () => {
  try {
    const raw = localStorage.getItem(getAnswersKey())
    if (raw) {
      const parsed = JSON.parse(raw)
      if (parsed && typeof parsed === 'object') {
        answers.value = parsed
        console.log('加载本地草稿答案成功')
      }
    }
    const t = localStorage.getItem(getTimeKey())
    if (t && exam.value?.timeLimit) {
      const saved = Number(t)
      const max = exam.value.timeLimit * 60 * 1000
      if (!Number.isNaN(saved) && saved > 0 && saved <= max) {
        timeRemaining.value = saved
        console.log('恢复剩余时间:', saved)
      }
    }
  } catch (e) {
    console.warn('加载本地草稿失败:', e)
  }
}

const saveDraft = () => {
  try {
    localStorage.setItem(getAnswersKey(), JSON.stringify(answers.value))
    if (exam.value?.timeLimit) {
      localStorage.setItem(getTimeKey(), String(timeRemaining.value))
    }
  } catch (e) {
    console.warn('保存本地草稿失败:', e)
  }
}

const clearDraft = () => {
  try {
    localStorage.removeItem(getAnswersKey())
    localStorage.removeItem(getTimeKey())
  } catch {}
}
const startExam = async () => {
  try {
    console.log('ExamTaking: 开始初始化考试，考试ID:', examId)
    
    // 检查登录状态
    if (!localStorage.getItem('access_token')) {
      ElMessage.error('请先登录后再参加考试')
      router.push('/login')
      return
    }
    
    console.log('ExamTaking: 开始考试API调用')
    // 开始考试
    record.value = await examApi.start(examId)
    console.log('ExamTaking: 考试记录创建成功:', record.value)
    
    console.log('ExamTaking: 获取考试信息和题目')
    // 获取考试信息和题目
    const [examRes, questionsRes] = await Promise.all([
      examApi.get(examId),
      examApi.getExamQuestions(examId)
    ])
    
    exam.value = examRes
    questions.value = Array.isArray(questionsRes) ? questionsRes : (questionsRes as any)?.data || []
    console.log('ExamTaking: 考试信息:', exam.value)
    console.log('ExamTaking: 题目列表:', questions.value)
    
    // 设置计时器
    if (exam.value.timeLimit) {
      timeRemaining.value = exam.value.timeLimit * 60 * 1000 // 转换为毫秒
      startTimer()
      console.log('ExamTaking: 计时器已启动，剩余时间:', timeRemaining.value)
    }
    
    // 恢复草稿（答案/时间）。如存在草稿，询问是否恢复
    const hadDraft = !!localStorage.getItem(getAnswersKey()) || !!localStorage.getItem(getTimeKey())
    if (hadDraft) {
      try {
        await ElMessageBox.confirm('检测到上次未提交的作答记录，是否恢复继续？', '恢复作答', {
          confirmButtonText: '恢复',
          cancelButtonText: '重新开始',
          type: 'info'
        })
        loadDraft()
      } catch {
        // 选择重新开始
        clearDraft()
      }
    } else {
      loadDraft()
    }
    
    ElMessage.success('考试已开始，祝您好运！')
  } catch (error) {
    console.error('ExamTaking: 开始考试失败:', error)
    ElMessage.error(getErrorMessage(error))
    router.back()
  }
}

const startTimer = () => {
  timer.value = setInterval(() => {
    if (timeRemaining.value > 0) {
      timeRemaining.value -= 1000
      // 持久化剩余时间，便于刷新恢复
      try { localStorage.setItem(getTimeKey(), String(timeRemaining.value)) } catch {}
    } else {
      // 时间到，自动提交
      ElMessage.warning('考试时间到，自动提交！')
      submitExam()
    }
  }, 1000)
}

const goToQuestion = (index: number) => {
  currentQuestionIndex.value = index
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

const nextQuestion = () => {
  if (questions.value && currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
  }
}

const saveAnswer = (questionId: number, answer: any) => {
  answers.value[questionId] = answer
  saveDraft()
}

// 解析选项数据
const parseOptions = (options: any) => {
  console.log('parseOptions input:', options, typeof options)
  
  if (typeof options === 'string') {
    try {
      const parsed = JSON.parse(options)
      console.log('parseOptions parsed:', parsed)
      return parsed
    } catch (e) {
      console.error('parseOptions parse error:', e)
      return {}
    }
  }
  return options || {}
}

// 依据题目ID生成稳定种子，确保在一次考试中刷新不改变顺序
const seededShuffle = (keys: string[], seed: number) => {
  // 线性同余生成器
  let s = seed % 2147483647
  if (s <= 0) s += 2147483646
  const rand = () => (s = (s * 16807) % 2147483647) / 2147483647
  const arr = [...keys]
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(rand() * (i + 1))
    ;[arr[i], arr[j]] = [arr[j], arr[i]]
  }
  return arr
}

const getShuffledOptions = (q: any) => {
  if (!q || !q.options) return [];
  
  const opts = parseOptions(q.options) || {};
  // 将选项标准化为数组，索引0=>A, 1=>B...
  const optionArray = Array.isArray(opts) ? opts : Object.values(opts);
  const letters = optionArray.map((_: any, idx: number) => String.fromCharCode(65 + idx));

  if (!q?.id || letters.length <= 1) return letters.map((k: string, i: number) => [k, optionArray[i]]);

  // 如果后端未启用乱序，也保持原顺序
  if (!exam.value?.shuffleOptions && !q.shuffleOptions) {
    return letters.map((k: string, i: number) => [k, optionArray[i]])
  }
  // 使用缓存顺序，避免刷新导致变化
  if (!optionOrderCache.value[q.id]) {
    optionOrderCache.value[q.id] = seededShuffle([...letters], Number(q.id))
  }
  const orderedKeys = optionOrderCache.value[q.id]
  return orderedKeys.map((k: string) => [k, optionArray[k.charCodeAt(0) - 65]])
}

const submitExam = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要提交考试吗？提交后无法修改答案。',
      '提交确认',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '继续答题',
        type: 'warning'
      }
    )
    
    submitting.value = true
    
    // 检查考试记录
    if (!record.value || !record.value.id) {
      console.error('考试记录无效:', record.value)
      ElMessage.error('考试记录无效，请重新开始考试')
      return
    }
    
    // 准备提交数据
    const submitData = {
      recordId: record.value.id,
      answers: Object.entries(answers.value).map(([questionId, answer]) => {
        let formattedAnswer = answer
        
        // 处理不同类型的答案格式
        if (Array.isArray(answer)) {
          // 多选题：转为逗号分隔字符串
          formattedAnswer = answer.join(',')
        } else if (typeof answer === 'boolean') {
          // 判断题：转为字符串
          formattedAnswer = answer.toString()
        } else {
          // 其他类型：转为字符串
          formattedAnswer = String(answer)
        }
        
        return {
          questionId: Number(questionId),
          answer: formattedAnswer
        }
      })
    }
    
    console.log('提交考试数据:', submitData)
    console.log('当前考试记录:', record.value)
    console.log('当前答案:', answers.value)
    
    const result = await examApi.submit(submitData)
    console.log('提交结果:', result)
    
    ElMessage.success('考试提交成功！')
    // 清理本地草稿
    clearDraft()
    router.push(`/exam-result/${result.id}`)
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交考试失败详细信息:', error)
      ElMessage.error('提交失败: ' + getErrorMessage(error))
    }
  } finally {
    submitting.value = false
  }
}

const getDifficultyColor = (difficulty: string) => {
  const colors = { EASY: 'success', MEDIUM: 'warning', HARD: 'danger' }
  return colors[difficulty as keyof typeof colors] || 'info'
}

const getDifficultyText = (difficulty: string) => {
  const texts = { EASY: '简单', MEDIUM: '中等', HARD: '困难' }
  return texts[difficulty as keyof typeof texts] || difficulty
}

// 生命周期
onMounted(() => {
  startExam()
})

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

// 页面离开前的确认
window.addEventListener('beforeunload', (e) => {
  if (record.value) {
    e.preventDefault()
    e.returnValue = '确定要离开考试页面吗？'
  }
})
</script>

<style scoped>
.exam-taking-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.exam-meta {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-top: 10px;
}

.questions-section {
  display: grid;
  grid-template-columns: 260px 1fr;
  gap: 16px;
}

.question-navigation {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.question-navigation .el-button {
  margin: 2px;
  width: 40px;
  height: 40px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.question-content {
  margin-bottom: 30px;
}

.question-text {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.options .option-item {
  display: block;
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  transition: all 0.2s;
}

.options .option-item:hover {
  border-color: #409eff;
  background: #f0f8ff;
}

.true-false .el-radio {
  margin: 0 20px 0 0;
}

.question-navigation-buttons {
  display: flex;
  justify-content: space-between;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.ka-aside { background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06); padding:12px; height: fit-content; position: sticky; top: 16px; }
.ka-timer { text-align:center; background:#f6f9ff; border:1px solid #e6eefb; border-radius:10px; padding:10px; margin-bottom:12px; }
.ka-timer .label{ color:#64748b; font-size:12px; }
.ka-timer .time{ font-size:24px; font-weight:700; color:#1865f2; }
.ka-timer .time.danger{ color:#e34d59; }
.ka-nav{ display:grid; grid-template-columns: repeat(5, 1fr); gap:8px; }
.ka-nav-btn{ height:36px; border:1px solid #e6eefb; background:#fff; border-radius:8px; cursor:pointer; }
.ka-nav-btn.active{ background:#1865f2; color:#fff; border-color:#1865f2; }
.ka-nav-btn.done{ background:#e8fff2; border-color:#b8f1d5; }
.ka-submit{ margin-top:12px; }

.exam-footer { display:none; }

.exam-footer .el-button {
  padding: 12px 30px;
  font-size: 16px;
}

@media (max-width: 900px){
  .questions-section{ grid-template-columns: 1fr; }
  .exam-footer{ display:block; text-align:center; padding:12px; position: sticky; bottom:0; background:#fff; box-shadow:0 -2px 6px rgba(0,0,0,0.08); }
}
</style>